package com.yogurt.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.yogurt.oss.service.OssService;
import com.yogurt.oss.utils.OssUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @Auther: 酸奶
 * @Date: 2020/07/08 15:28
 * @Description: oss上传实现类
 */

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadAvatar(MultipartFile file) {
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = OssUtils.END_POINT;
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        String accessKeyId = OssUtils.ACCESS_KEY_ID;
        String accessKeySecret = OssUtils.ACCESS_KEY_SECRET;
        String bucketName = OssUtils.BUCKET_NAME;


        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            //获取文件输入流
            InputStream inputStream = file.getInputStream();
            //UUID
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //获取文件名称
            String filename = file.getOriginalFilename();
            filename = uuid + filename;
            //获取当前日期,根据日期进行分类
            String datePath = new DateTime().toString("yyyy/MM/dd");
            //拼接文件名称
            filename = datePath + "/" + filename;
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, filename, inputStream);
            // 上传文件至阿里云。
            ossClient.putObject(putObjectRequest);
            // 关闭OSSClient。
            ossClient.shutdown();

            //默认上传给文件路径：https://guli-eduproject.oss-cn-beijing.aliyuncs.com/timg.jpg
            //获取url地址
            String url = "https://" + bucketName + "." + endpoint + "/" + filename;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
